package com.coder.books.thinkinjava.concurrency;

import java.util.concurrent.TimeUnit;

import static com.coder.util.Print.println;

/**
 *
 * @author yuhushuan
 * @date 2020/9/3 20:57
 */
class NeedsCleanup {
    private final int id;

    public NeedsCleanup(int ident) {
        id = ident;
        println("NeedsCleanup " + id);
    }

    public void cleanup() {
        println("Cleaning up " + id);
    }
}

class Blocked3 implements Runnable {
    private volatile double d = 0;

    @Override
    public void run() {
        try {
            while (!Thread.interrupted()) {
                // point1
                NeedsCleanup n1 = new NeedsCleanup(1);
                try {
                    println("Sleeping");
                    TimeUnit.SECONDS.sleep(1);
                    // point2
                    NeedsCleanup n2 = new NeedsCleanup(2);

                    try {
                        println("Calculating");
                        for (int i = 1; i < 250000000; i++) {
                            d = d + (Math.PI + Math.E) / d;
                        }
                        println("Finished time-consuming operation");
                    } finally {
                        n2.cleanup();
                    }
                } finally {
                    n1.cleanup();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class InterruptingIdiom {
    public static void main(String[] args) throws InterruptedException {
        Thread t = new Thread(new Blocked3());
        t.start();
        TimeUnit.MILLISECONDS.sleep(1100);
        t.interrupt();
    }
}
